unit Visual;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, StdCtrls;

const
  l=10;
  k=5;
  n=50;

type
  TForm1 = class(TForm)
    Image1: TImage;
    Button1: TButton;
    Timer1: TTimer;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure Image1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  m:array of integer;
  a, b:integer;
  flag:boolean;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var i:integer;
begin
  randomize;
  for i:=0 to n-1 do
    m[i]:=random(300);
  a:=0;
  b:=0;
  flag:=false;
  Timer1.Enabled:=true;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  setlength(m, n);
end;

procedure TForm1.Timer1Timer(Sender: TObject);
var t,i:integer;
begin
  if m[a]>m[a+1] then
  begin
    t:=m[a];
    m[a]:=m[a+1];
    m[a+1]:=t;
    flag:=true
  end;
  Form1.Image1.Canvas.Rectangle(ClientRect);
  for i:=0 to n-1 do
    Form1.Image1.Canvas.Rectangle(l*m[i],k,l*m[i]+l ,k*m[i]+k );
  a:=a+1;
  if a=n-1-b then
  begin
    a:=0;
    b:=b+1;
  end;
  if (b=n-1) or not flag then
  begin
    Timer1.Enabled:=False;
  end
  else
    flag:=false;
end;

end.
